package com.gwq.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gwq.entity.SysMenu;
import com.gwq.entity.SysRole;
import com.gwq.entity.SysUser;
import com.gwq.mapper.SysUserMapper;
import com.gwq.param.UserParam;
import com.gwq.service.SysMenuService;
import com.gwq.service.SysRoleService;
import com.gwq.service.SysUserService;
import com.gwq.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gwq
 * @since 2022-06-07
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    SysRoleService roleService;

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SysMenuService sysMenuService;

    @Autowired
    RedisUtil redisUtil;


    @Override
    public SysUser getByUserName(String username) {
        SysUser sysUser = getOne(new QueryWrapper<SysUser>().eq("user_name", username));
//        SysRole sysRole = roleService.getUserType(sysUser.getId());
//        if(sysRole!=null){
//            if(sysRole.getCode().equalsIgnoreCase("normal")){
//                sysUser.setUserType(2);
//            }else{
//                sysUser.setUserType(2);
//            }
//        }
        return sysUser;
    }


    @Override
    public String getUserAuthorityInfo(String userId) {
        SysUser sysUser = sysUserMapper.selectById(userId);
        // 获取角色
        String authority = "";
        if(redisUtil.hasKey("GrantedAuthority:"+sysUser.getUserName())){
            authority = (String) redisUtil.get("GrantedAuthority:" + sysUser.getUserName());
        }else {
            // 获取菜单操作权限
            List<SysRole> roles = roleService.list(new QueryWrapper<SysRole>().inSql("id", "select role_id from sys_user_role where user_id = '" + userId+"'"));
            if(roles.size() > 0){
                String rolesCodes = roles.stream().map(r -> "ROLE_" + r.getCode()).collect(Collectors.joining(","));
                authority = rolesCodes;
            }
            // 获取菜单
            List<String> menuIds = sysUserMapper.getNavMenuIds(userId);
            if(menuIds.size() > 0){
                List<SysMenu> sysMenus = (List<SysMenu>) sysMenuService.listByIds(menuIds);
                String menuPerms = sysMenus.stream().map(m -> m.getPerms()).collect(Collectors.joining(","));
                authority = authority.concat(",").concat(menuPerms);
            }
            redisUtil.set("GrantedAuthority:"+sysUser.getUserName(), authority, 60 * 60);
        }
        return authority;
    }

    @Override
    public void clearUserAuthorityInfo(String userName) {
        redisUtil.del("GrantedAuthority:"+userName);
    }

    @Override
    public void clearUserAuthorityInfoByRoleId(String roleId) {
        List<SysUser> sysUsers = this.list(new QueryWrapper<SysUser>().inSql("id", "select user_id from sys_user_role where role_id = " + roleId));
        sysUsers.forEach(u -> {
            this.clearUserAuthorityInfo(u.getUserName());
        });
    }

    @Override
    public void clearUserAuthorityInfoByMenuId(String menuId) {
        List<SysUser> sysUsers = sysUserMapper.listByMenuId(menuId);
        sysUsers.forEach(u -> {
            this.clearUserAuthorityInfo(u.getUserName());
        });
    }

    @Override
    public Page<SysUser> pageUser(UserParam userParam) {
        Page<SysUser> page = new Page<>(userParam.getPage(),userParam.getSize());
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(userParam.getUserName()), "user_name", userParam.getUserName());
        return (Page<SysUser>) baseMapper.selectPage(page,queryWrapper);
    }
}
